package com.example.myapplication.part03.part09;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.myapplication.R;

import java.util.ArrayList;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    // 请求码定义
    private static final int REQ_CODE_ACCOUNT = 101;
    private static final int REQ_CODE_PASSWORD = 102;
    private static final int PERM_REQ_CODE = 201;

    // UI组件
    private EditText etAccount, etPassword;
    private TextToSpeech ttsEngine;
    private int activeInputType = REQ_CODE_ACCOUNT;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etAccount = findViewById(R.id.login_id);
        etPassword = findViewById(R.id.login_password);

        @SuppressLint("WrongViewCast") ImageButton btnVoiceAccount = findViewById(R.id.btnSubtract);
        @SuppressLint("WrongViewCast") ImageButton btnVoicePassword = findViewById(R.id.login_password);
        Button btnLogin = findViewById(R.id.login_button);

        btnVoiceAccount.setOnClickListener(v -> {
            activeInputType = REQ_CODE_ACCOUNT;
            if (checkPermission()) {
                startSpeechRecognition();
            } else {
                requestPermission();
            }
        });

        btnVoicePassword.setOnClickListener(v -> {
            activeInputType = REQ_CODE_PASSWORD;
            if (checkPermission()) {
                startSpeechRecognition();
            } else {
                requestPermission();
            }
        });

        btnLogin.setOnClickListener(v -> {
            // 处理登录逻辑
            String account = etAccount.getText().toString();
            String password = etPassword.getText().toString();
            Toast.makeText(this, "账号: " + account + ", 密码: " + password, Toast.LENGTH_SHORT).show();
        });

        ttsEngine = new TextToSpeech(this, status -> {
            if (status == TextToSpeech.SUCCESS) {
                int result = ttsEngine.setLanguage(Locale.CHINA);
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    Toast.makeText(this, "不支持该语言", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "语音合成初始化失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private boolean checkPermission() {
        return ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
    }

    private void requestPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
            new AlertDialog.Builder(this)
                    .setTitle("权限请求")
                    .setMessage("需要录音权限以使用语音输入功能")
                    .setPositiveButton("确定", (dialog, which) ->
                            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, PERM_REQ_CODE))
                    .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                    .show();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, PERM_REQ_CODE);
        }
    }

    private void startSpeechRecognition() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.CHINA);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "请说话...");
        startActivityForResult(intent, activeInputType);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            if (result != null && !result.isEmpty()) {
                String text = result.get(0);
                if (requestCode == REQ_CODE_ACCOUNT) {
                    etAccount.setText(text);
                } else if (requestCode == REQ_CODE_PASSWORD) {
                    etPassword.setText(text);
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERM_REQ_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startSpeechRecognition();
            } else {
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
                    new AlertDialog.Builder(this)
                            .setTitle("权限被拒绝")
                            .setMessage("你已拒绝录音权限，若要使用语音输入功能，请在设置中开启权限")
                            .setPositiveButton("去设置", (dialog, which) -> {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);
                            })
                            .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                            .show();
                } else {
                    Toast.makeText(this, "权限被拒绝，无法使用语音输入", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (ttsEngine != null) {
            ttsEngine.stop();
            ttsEngine.shutdown();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 从设置返回时检查权限状态
        if (checkPermission()) {
            findViewById(R.id.btnSubtract).setEnabled(true);
            findViewById(R.id.login_password).setEnabled(true);
        }
    }
}